<!--文档管理页-->
<template>
  <a-layout>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form layout="inline" :model="param">
            <a-form-item>
              <a-button type="primary" @click="handleQuery()">
                查询
              </a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="add()">
                新增
              </a-button>
            </a-form-item>
          </a-form>
          <!--
              这里:defaultExpandAllRows="true"配置是没有效果的，他不是动态监听的，加个v-if来判断有值时才加载
          -->
          <a-table
              v-if="level1.length > 0"
              :columns="columns"
              :row-key="record => record.id"
              :data-source="level1"
              :pagination="false"
              :loading="loading"
              size="small"
              :defaultExpandAllRows="true"
          >
            <template v-slot:action="{ text, record }">
              <a-space size="small">
                <a-button type="primary" @click="edit(record)">
                  编辑
                </a-button>
                <a-popconfirm
                    title="删除后不可恢复，确认删除？"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="showDeleteConfirm(record.id)"
                >
                  <a-button danger>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-col>
        <a-col :span="16">
          <p>
            <a-form layout="inline" :model="param">
              <a-form-item>
                <a-button type="primary" @click="handleOk">
                  保存
                </a-button>
              </a-form-item>
            </a-form>
          </p>
          <a-form
              :model="doc"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
              autocomplete="off"
              layout="vertical"
          >
            <a-form-item>
              <a-input v-model:value="doc.name" placeholder="名称"/>
            </a-form-item>
            <a-form-item>
              <!-- 树选择 -->
              <a-tree-select
                  v-model:value="doc.parent"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeSelectData"
                  placeholder="请选择父分类"
                  tree-default-expand-all
                  :field-names="{ children: 'children', label: 'name', value: 'id' }"
                  tree-node-filter-prop="name"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model:value="doc.sort" placeholder="顺序"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handlePreviewContent">
                文档预览
              </a-button>
            </a-form-item>
            <!-- 富文本 -->
            <a-form-item>
              <div id="content">
                <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                />
                <Editor
                    style="height: 500px; overflow-y: hidden;"
                    v-model="valueHtml"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                />
              </div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-layout-content>
    <!-- 文本预览组件 -->
    <a-drawer
        width="900px"
        v-model:open="drawVisible"
        class="custom-class"
        root-class-name="root-class-name"
        title="文本预览"
        placement="right"
        @close="onDrawerClose"
    >
      <div class="editor-content-view" :innerHTML="previewHtml"></div>
    </a-drawer>
  </a-layout>
</template>
<script lang="ts">
import {SmileOutlined, DownOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {defineComponent, onMounted, ref, createVNode, shallowRef, onBeforeUnmount} from 'vue';
import axios from "axios";
import {message, Modal} from "ant-design-vue";
import {Tool} from "@/util/tool";
import {useRoute} from 'vue-router';
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import store from "@/store";

export default defineComponent({
  name: 'admin-doc',
  components: {
    SmileOutlined,
    DownOutlined,
    Editor,
    Toolbar
  },
  setup() {
    const route = useRoute();
    // 树形结构
    const level1 = ref();
    level1.value = []
    // 父文档下拉树形选择框
    const treeSelectData = ref();
    treeSelectData.value = []
    // 文档查询参数封装
    const param = ref();
    param.value = {};
    const loading = ref(false);

    const columns = [
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    /**
     * 数据查询
     **/
    const handleQuery = () => {
      loading.value = true;
      // 这里get传参不用拼接方法 使用params固定参数配置
      axios.get("/doc/all/" + route.query.ebookId).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          //level1.value = data.content; // 这是数组结构
          level1.value = Tool.array2Tree(data.content, 0); // 自己处理成树形结构
          console.log("树形结构：", level1.value);

          // 父文档下拉框初始化 相当于点击新增
          treeSelectData.value = Tool.copy(level1.value);
          if (Tool.isEmpty(treeSelectData.value)) {
            treeSelectData.value = [];
          }
          // 为树选择一个‘无’
          treeSelectData.value.unshift({id: 0, name: '无'})
        } else {
          message.error(data.message);
        }
      });
    }

    /**
     * 内容查询 - 富文本
     **/
    const handleQueryContent = () => {
      // 这里get传参不用拼接方法 使用params固定参数配置
      axios.get("/doc/find-content/" + doc.value.id).then((response) => {
        const data = response.data;
        if (data.success) {
          valueHtml.value = data.content;
        } else {
          message.error(data.message);
        }
      });
    }

    // --------表单数据-----------
    const doc = ref();
    doc.value = {
      ebookId: route.query.ebookId
    };
    const edit = (record: any) => {
      valueHtml.value = "";
      // doc.value = record; 此写法会是响应式的 编辑应该是编辑赋值的对象，通过JSON方法实现  这里封装成工具类
      // doc.value = JSON.parse(JSON.stringify(record));
      doc.value = Tool.copy(record);
      handleQueryContent();
      treeSelectData.value = Tool.copy(level1.value)
      // 为选择树添加一个 “无”
      treeSelectData.value.unshift({id: 0, name: '无'})
      // 不能选择当前节点及其所有子孙节点，作为父节点，会使树断开
      setDisable(treeSelectData.value, record.id);
    };
    // 编辑框确认
    const handleOk = () => {
      doc.value.content = valueHtml;
      // 不像get,传params键
      axios.post("/doc/save", doc.value).then((resp) => {
        const data = resp.data;
        // 成功
        if (data.success) {
          message.success("保存成功");
          // 刷新列表
          handleQuery();
        } else {
          message.error(data.message);
        }
      })
    };

    // 新增文档
    const add = () => {
      doc.value = {
        ebookId: route.query.ebookId
      };
      valueHtml.value = "";
      treeSelectData.value = Tool.copy(level1.value)
      // 为选择树添加一个 “无”
      if (Tool.isEmpty(treeSelectData.value)) {
        treeSelectData.value = [];
      }
      treeSelectData.value.unshift({id: 0, name: '无'})
    };

    const showDeleteConfirm = (id: number) => {
      ids = [];
      delNames = [];
      getDeleteIds(level1.value, id);
      Modal.confirm({
        title: '确认删除此文档吗?',
        icon: createVNode(ExclamationCircleOutlined),
        content: delNames,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          handleDelete(id);
        },
        onCancel() {
          delNames = [];
          console.log('Cancel');
        },
      });
    };
    const handleDelete = (id: number) => {
      // 如 /doc/delete/1,2.3
      axios.delete("/doc/delete/" + ids.join(",")).then((resp) => {
        const data = resp.data;
        // 成功
        if (data.success) {
          // 刷新列表
          handleQuery();
        }
      });
    }
    let ids: Array<number> = [];
    // 二次确认框提示包含删除的名字
    let delNames: Array<string> = [];
    const getDeleteIds = (treeDocData: any, id: any) => {
      // 遍历数组，遍历某一层节点
      for (let i = 0; i < treeDocData.length; i++) {
        const node = treeDocData[i];
        if (node.id === id) {
          // 如果当前节点 就是目标节点
          console.log("delete", node);
          ids.push(id);
          delNames.push('[' + treeDocData[i].name + ']' + " ")
          // 遍历其所有子节点
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getDeleteIds(children, children[j].id);
            }
          }
        } else {
          // 如果当层没有目标节点，则到子节点在找找看
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getDeleteIds(children, id);
          }
        }
      }
    }

    /**
     * 将某节点及其子孙节点全部置为disabled
     * 看似两层递归
     * 难度：5颗星
     */
    const setDisable = (treeSelectData: any, id: any) => {
      // 遍历数组，遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点 就是目标节点
          console.log("disabled", node);
          node.disabled = true;

          // 遍历其所有子节点，并将其子节点全部加上disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              setDisable(children, children[j].id);
            }
          }
        } else {
          // 如果当层没有目标节点，则到子节点在找找看
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisable(children, id);
          }
        }
      }
    }

    /**
     * 富文本文档预览
     */
    const drawVisible = ref(false);
    const previewHtml = ref();
    const handlePreviewContent = () => {
      previewHtml.value = valueHtml.value;
      drawVisible.value = true;
    }
    const onDrawerClose = () => {
      drawVisible.value = false;
    }

    // ------- wangEditor --------配置
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML 这就是富文本，它不包含样式，只是html代码
    const valueHtml = ref()

    const token = store.state.user.token;
    type InsertFnType = (url: string) => void
    const toolbarConfig = {}
    const editorConfig = {
      placeholder: '请输入内容...',
      MENU_CONF: {
        // 配置图片上传
        uploadImage: {
          fieldName: 'file',
          server: 'http://localhost:8888/file-upload',
          // 单个文件的最大体积限制，默认为 2M
          maxFileSize: 40 * 1024 * 1024, // 4M

          headers: {
            token: token,
          },
          // 自定义插入图片
          customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
            // 从 res 中找到 url alt href ，然后插入图片
            const url = res.content;
            insertFn(url)
          },
        }
      }
    }
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor: any) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    onMounted(() => {
      handleQuery();
    });

    return {
      level1,
      param,
      loading,
      columns,
      doc,
      edit,
      add,
      handleOk,
      handleDelete,
      handleQuery,
      treeSelectData,
      showDeleteConfirm,

      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      handlePreviewContent,
      onDrawerClose,
      drawVisible,
      previewHtml
    };
  },
});
</script>


<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>